<?php
namespace Home\Controller;
use Think\Controller;

class GuiderController extends FrontController {
	public function list($order = 'id desc') {
		//sui
		$this->assign('title', '定制导游');
		$sui = [
			'customized' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		//搜索
		$_GET['searchMap']['state'] = '正常';
		$searchMap = $_GET['searchMap'];
		if ($searchMap) {
			foreach ($searchMap as $field => $value) {
				if (!$value) {
					unset($searchMap[$field]);
				} else {
					$searchMap[$field] = ['LIKE', '%'.$value.'%'];
				}
			}
			if ($searchMap['age']) {
				$searchMap['age'] = ['BETWEEN', $searchMap['age']];
			}
		}
		$order = str_replace('id', 'user.id', $order);
		//获取导游信息
		$model = D('UserGuider');
		$count = $model->join('user on user_guider.principal_id = user.id')->where($searchMap)->count();
		$page = new \Think\SuiPage($count, C('PAGE_NUM'));
		$show = $page->show();
		$list = $model->order($order)->where($searchMap)->join('user on user_guider.principal_id = user.id')->limit($page->firstRow . ',' . $page->listRows)->select();
		$this->assign('list', $list);
		$this->assign('page', $show);
		$this->display();
	}

	public function detail($id) {
		//导游信息
		$model = D('UserGuider')->join('user on user_guider.principal_id = user.id')->where(['principal_id' => $id])->find();
		$this->assign('model', $model);
		//sui
		$this->assign('title', $model['name'] . '-导游详情');
		$sui = [
			'customized' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		$this->display();
	}

	public function contractShow() {
		//sui
		$this->assign('title', '合同内容');
		$sui = [
			'customized' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		//定制导游合同
		$contract = D('Contract')->where(['type'=>'定制导游'])->find();
		$this->assign('contract', $contract);
		$this->display();
	}

	public function buy($id) {
		if (!session('用户')) {
			session('afterLogin', U('Guider/buy', ['id'=>$id]));
			$this->redirect('User/login', ['afterLogin'=>1]);
		}


		//导游信息
		$model = D('UserGuider')->join('user on user_guider.principal_id = user.id')->where(['principal_id' => $id])->find();
		$this->assign('model', $model);
		//sui
		$this->assign('title', $model['name'] . '-导游详情');
		$sui = [
			'customized' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		//当前登录信息
		$this->assign('user', session('用户'));
		if (IS_POST) {
			//判断游客数量
			if (count($_POST['tourist']) == 0) {
				$this->error('至少选择一个游客!');
			}
			//计算保险价格
			$insurancePrice = 0;
			foreach ($_POST['insurance'] as $insuranceId) {
				$insurance = D('Insurance')->find($insuranceId);
				$insurancePrice += $insurance['price'] * count($_POST['tourist']);
			}

			//创建定制导游订单
			$model = D('CustomizedGuider');
			$_POST['user_id'] = session('用户')['id'];
			$guider = D('UserGuider')->join('user on user_guider.principal_id = user.id')->where(['principal_id' => $id])->find();
			//出行时间段
			$duringTime = strtotime($_POST['end_time']) - strtotime($_POST['start_time']);
			$duringTime = $duringTime / 24 / 60 / 60 + 1;
			$_POST['name'] = $guider['name'] . '带领的' . $guider['location'] . $duringTime . '天旅行';
			$_POST['price'] = $guider['price'];
			$_POST['amount'] = $guider['price'] * $duringTime +$insurancePrice;
			if (!$model->create()) {
				$this->error($model->getError());
				return false;
			}
			$newId = $model->add();
			//保险订单
			foreach ($_POST['tourist'] as $touristId) {
				$tourist = D('Tourist')->find($touristId);
				unset($data);
				$data['user_id'] = session('用户')['id'];
				$data['tourist_id'] = $touristId;
				$data['order_type'] = 'customized_guider';
				$data['order_id'] = $newId;
				D('TouristOrder')->data($data)->add();
				foreach ($_POST['insurance'] as $insuranceId) {
					unset($data);
					$data['user_id'] = session('用户')['id'];
					$data['insurance_id'] = $insuranceId;
					$data['order_type'] = 'customized_guider';
					$data['order_id'] = $newId;
					$data['name'] = $tourist['name'];
					$data['phone'] = $tourist['phone'];
					$data['id_number'] = $tourist['id_number'];
					D('InsuranceOrder')->data($data)->add();
				}
			}
			//通知导游
			notice(session('用户')['id'], $guider['principal_id'], '收到新的定制导游订单', session('用户')['name'] . '的' . $guider['location'] . $duringTime . '日导游订单');
			//通知admin
			notice(session('用户')['id'], 1, '有新的定制导游订单', session('用户')['name'] . '的' . $guider['location'] . $duringTime . '日导游订单');
			$this->success('导游定制成功!', U('User/CustomizedGuider'));
		}
		$this->display();
	}

	public function contract($id) {
		//sui
		$this->assign('title', '合同内容');
		$sui = [
			'customized' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);

		if (IS_POST) {
			if ($_POST['contractOrderId'] != '') {
				// 修改补充合同
				D('ContractOrder')->where(['id'=>$_POST['contractOrderId']])->data(['buyer_content'=>$_POST['buyer_content'], 'buyer_contract_state'=>'未签署', 'seller_contract_state'=>'未签署', 'buyer_contract_time'=>0, 'seller_contract_time'=>0])->save();
				$this->success('更新成功!');	
			} elseif ($_POST['user_contract']) {
				//修改原有合同
				D('CustomizedGuider')->where(['id'=>$id])->data(['user_contract'=>$_POST['user_contract'], 'user_contract_state'=>'未签署', 'guider_contract_state'=>'未签署', 'user_contract_time'=>0, 'guider_contract_time'=>0])->save();
				$this->success('更新成功!');	
			} else {
				//增加合同
				//增加notice
				$customizedGuider = D('CustomizedGuider')->find($id);
				notice(1, $customizedGuider['guider_user_id'], '系统通知', '有新的补充合同，请尽快查看！');
				D('ContractOrder')->add($_POST);
			}
			$this->success('合同补充成功!');
		}

		// 订单信息
		$custonizeguider = D('CustomizedGuider')->find($id);
		if (!$custonizeguider['content']) {
			$this->error('请待导游编辑好合同、日程后再进行确认!');
		}
		$this->assign('custonizeguider', $custonizeguider);
		//导游信息
		$guider = D('UserGuider')->join('user on user.id=principal_id')->where(['principal_id' => $custonizeguider['guider_user_id']])->find();
		$this->assign('guider', $guider);
		// 合同信息
		$contract = D('Contract')->where(['type' => '定制导游'])->find();
		$this->assign('contract', $contract['content']);


		$this->display();
	}

	public function pay($id) {
		$cunstomizedGuider = D('CustomizedGuider')->where(['id' => $id])->find();
        if (!$this->isWeixin()) {
            $this->redirect('/Api/Alipay/pay', ['out_trade_no'=>'CustomizedGuider-'.$id, 'subject'=>$cunstomizedGuider['name'], 'total_fee'=>$cunstomizedGuider['amount']]);
        } else {
            $out_trade_no = 'CustomizedGuider-'.$id;
            $subject = $cunstomizedGuider['name'];
            $total_fee = $cunstomizedGuider['amount'];
            session('wxpay_out_trade_no', $out_trade_no);
            session('wxpay_subject', $subject);
            session('wxpay_total_fee', $total_fee);
            $this->redirect('/Api/Wxpay/pay');
        }
	}

	public function sign($id, $type='order') {
		if ($type == 'contractOrder') {
			//附加合同签约
			D('ContractOrder')->where(['id' => $id])->data(['buyer_contract_state' => '已签署', 'buyer_contract_time'=>time()])->save();
		} elseif ($type == 'order'){
			// order本身签署
			//修改游客签约状态
			D('CustomizedGuider')->where(['id' => $id])->data(['user_contract_state' => '已签署', 'user_contract_time'=>time()])->save();
			$customizeGuider = 	D('CustomizedGuider')->where(['id' => $id])->find();
			if ($customizeGuider['guider_contract_state'] == '已签署') {
				D('CustomizedGuider')->where(['id' => $id])->data(['state' => '待支付'])->save();
			}
		}

		$this->success('签约成功!', U('User/CustomizedGuider'));
	}

	public function comment($id) {
		//sui
		$this->assign('title', '评价导游');
		$sui = [
			'customized' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		// 订单信息
		$custonizeguider = D('CustomizedGuider')->find($id);
		$this->assign('custonizeguider', $custonizeguider);
		//导游信息
		$guider = D('UserGuider')->join('user on user.id=principal_id')->where(['principal_id' => $custonizeguider['guider_user_id']])->find();
		$this->assign('guider', $guider);
		if (IS_POST) {
			//创建评价
			$model = D('Comment');
			$_POST['user_id'] = session('用户')['id'];
			$_POST['commented_user_id'] = $guider['principal_id'];
			$_POST['order_type'] = 'CustomizedGuider';
			$_POST['order_id'] = $id;
			if (!$model->create()) {
				$this->error($model->getError());
				return false;
			}
			$model->add();
			//通知导游
			notice(session('用户')['id'], $guider['principal_id'], '收到新的评价', '收到新的评价，请查看');
			// 完成订单
			D('CustomizedGuider')->where(['id' => $id])->data(['state' => '已完成'])->save();
			//增加导游人气
			D('UserGuider')->where(['principal_id' => $custonizeguider['guider_user_id']])->data(['amount' => $guider['amount'] + 1])->save();
			//===金额相关===
			//计算保险价格
			$insurancePrice = 0;
			$insuranceOrders = D('InsuranceOrder')->where(['order_type'=>'customized_guider', 'order_id'=>$custonizeguider['id']])->select();
			foreach ($insuranceOrders as $insuranceOrder) {
				// $touristCount = D('TouristOrder')->where(['order_type'=>'customized_guider', 'order_id'=>$custonizeguider['id']])->count();
				$insurance = D('Insurance')->find($insuranceOrder['insurance_id']);
				$insurancePrice += $insurance['price'];
			}

			unset($data);
			if ($_POST['score'] > 3) {
				//给导游增加余额
				$userGuider = D('User')->find($guider['principal_id']);
				$newBalance = $userGuider['balance']+$custonizeguider['amount']-$insurancePrice;
				D('User')->where(['id'=>$guider['principal_id']])->data(['balance'=>$newBalance])->save();
				$data['remark'] = '用户评价订单-'.$custonizeguider['name'];

			} else {
				$data['remark'] = '用户评价订单-'.$custonizeguider['name'].'-差评未支付';
			}
			//给导游增加金额记录
            $data['user_id'] = $custonizeguider['guider_user_id'];
            $data['pay_type'] = '-';
            $data['amount'] = $custonizeguider['amount']-$insurancePrice;
            $data['order_type'] = 'CustomizedGuider';
            $data['order_id'] = $custonizeguider['id'];
            D('Finance')->create($data);
            D('Finance')->add();

			//给用户增加积分
        	$user = D('User')->find(session('用户')['id']);
        	$newCredit = $user['credit'] + $custonizeguider['amount'];
        	D('User')->where(['id'=>session('用户')['id']])->data(['credit'=>$newCredit])->save();
			//增加积分记录
        	unset($data);
        	$data['user_id'] = session('用户')['id'];
        	$data['amount'] = $custonizeguider['amount'];
        	$data['remark'] = '定制导游';
        	D('CreditRecord')->create($data);
        	D('CreditRecord')->add();

			$this->success('评价成功!', U('User/CustomizedGuider'));
		}
		$this->display();
	}

	public function complaint($id) {
		//sui
		$this->assign('title', '投诉导游');
		$sui = [
			'customized' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		//检查是否已经发起过投诉
		$complaint = D('Complaint')->where(['order_id' => $id])->find();
		if ($complaint) {
			$this->assign('complaint', $complaint);
		}
		// 订单信息
		$custonizeguider = D('CustomizedGuider')->find($id);
		$this->assign('custonizeguider', $custonizeguider);
		//导游信息
		$guider = D('UserGuider')->join('user on user.id=principal_id')->where(['principal_id' => $custonizeguider['guider_user_id']])->find();
		$this->assign('guider', $guider);
		if (IS_POST) {
			//创建投诉
			$model = D('Complaint');
			$_POST['user_id'] = session('用户')['id'];
			$_POST['order_type'] = 'CustomizedGuider';
			$_POST['order_id'] = $id;
			if (!$model->create()) {
				$this->error($model->getError());
				return false;
			}
			$model->add();
			//通知管理员
			notice(session('用户')['id'], 1, '收到新的投诉', '收到新的投诉，请查看');
			$this->success('投诉成功,请等待处理!', U('User/CustomizedGuider'));
		}
		$this->display();
	}

	public function CommentList($id) {
		//sui
		$this->assign('title', '导游评价');
		$sui = [
			'customized' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		//获取当前导游的所有评论和订单信息
		$model = D('Comment');
		$count = $model->join('customized_guider on order_id=customized_guider.id')->order('order_id desc')->where(['commented_user_id' => $id])->count();
		$page = new \Think\SuiPage($count, C('PAGE_NUM'));
		$show = $page->show();
		$list = $model->field('customized_guider.name as name, comment.order_id as order_id, score, is_complusive, is_guide, is_service, is_satisfy, is_contract, comment.content as content, comment.create_time as create_time')->join('customized_guider on order_id=customized_guider.id')->order('order_id desc')->where(['commented_user_id' => $id])->limit($page->firstRow . ',' . $page->listRows)->select();
		$this->assign('list', $list);
		$this->assign('page', $show);
		$this->display();
	}

}
